import SignRecord from '../model/SignRecord'
import UserModel from '../model/User'
import UserCollectsModel from '../model/UserCollect'
import { getJWTPayload } from '../common/utils'
import { setValue, getValue, delValue } from '../config/RedisConfig'
import mainEmail from '../config/Mailer'
import jwt from 'jsonwebtoken'
import moment from 'moment'
import { v4 as uuidv4 } from 'uuid'
import config from '@/config/index.js'
import bcryptjs from 'bcryptjs'
import PostModel from '@/model/Post'
import CommentModel from '@/model/Comment'
class UserController {
  async userSign (ctx) {
    const obj = await getJWTPayload(ctx.header.authorization)
    const record = await SignRecord.findByUid(obj._id)
    const user = await UserModel.findById(obj._id)
    let result = {}
    let newRecord = ''
    if (record) {
      if (
        moment(record.created).format('YYYY-MM-DD') ===
        moment().format('YYYY-MM-DD')
      ) {
        // 用户已经签到过
        ctx.body = {
          code: 500,
          msg: '用户已经签到',
          favs: user.favs,
          count: user.count
        }
        return
      } else {
        // 没有签到
        let count = user.count
        let fav = 0

        if (
          moment(record.created).format('YYYY-MM-DD') ===
          moment().subtract(1, 'days').format('YYYY-MM-DD')
        ) {
          // 连续签到
          count++
          if (count < 5) {
            fav = 5
          } else if (count >= 5 && count < 15) {
            fav = 10
          } else if (count >= 15 && count < 30) {
            fav = 15
          } else if (count >= 30 && count < 100) {
            fav = 20
          } else if (count >= 100 && count < 365) {
            fav = 30
          } else if (count >= 365) {
            fav = 50
          }
        } else {
          // 用户中断
          count = 1
          fav = 5
        }
        newRecord = new SignRecord({
          favs: fav,
          uid: obj._id
        })
        newRecord.save()
        await UserModel.updateOne(
          {
            _id: obj._id
          },
          {
            $set: { count },
            $inc: { favs: fav }
          }
        )
        result = {
          favs: user.favs + fav,
          count
        }
      }
    } else {
      // 记录不存在
      await UserModel.updateOne(
        {
          _id: obj._id
        },
        {
          $set: { count: 1 },
          $inc: { favs: 5 }
        }
      )
      newRecord = await new SignRecord({
        uid: obj._id,
        favs: 5
      })
      result = {
        count: 1,
        favs: user.favs + 5
      }
      newRecord.save()
    }
    ctx.body = {
      ...result,
      lastSign: newRecord.created,
      msg: '签到成功',
      code: 200
    }
  }

  async updateUserInfo (ctx) {
    const { body } = ctx.request
    const obj = await getJWTPayload(ctx.header.authorization)
    const user = await UserModel.findOne({ _id: obj._id })
    let msg = ''
    if (user.username && body.username && user.username !== body.username) {
      // 更改了邮箱，需要发送邮件通知
      const key = uuidv4()
      const token = jwt.sign({ _id: user._id }, config.JWT_SECRET, {
        expiresIn: 60 * 30
      })
      setValue(key, token, 30 * 60)
      await mainEmail({
        type: 'email',
        key,
        data: {
          key,
          username: body.username
        },
        email: user.username,
        code: 1234,
        expire: moment().add(30, 'minutes').format('YYYY-MM-DD hh:mm:ss'),
        user: user.name
      })
      msg = '更新基础数据成功,已发送更改邮箱邮件，请到邮箱进行点击更改邮箱'
    }
    const deleteFields = ['username', 'password', 'mobile']
    deleteFields.forEach((item) => {
      delete body[item]
    })
    const res = await UserModel.updateOne({ _id: obj._id }, body)
    if (res.n === 1 && res.ok === 1) {
      ctx.body = {
        code: 200,
        msg: msg === '' ? '更新成功 ' : msg
      }
    } else {
      ctx.body = {
        code: 500,
        msg: '更新失败'
      }
    }
  }

  async updateEmail (ctx) {
    const body = ctx.query
    if (body.key && body.username) {
      const token = await getValue(body.key)
      if (!token) {
        ctx.body = {
          code: 500,
          msg: '参数错误'
        }
        return
      }
      const obj = await getJWTPayload('Bearer ' + token)
      const user = await UserModel.findOne({ username: body.username })
      if (user && user._id !== obj._id) {
        ctx.body = {
          code: 500,
          msg: '该邮箱已存在，无法更新'
        }
        return
      }
      const res = await UserModel.updateOne({
        _id: obj._id
      }, {
        username: body.username
      })
      if (res.n === 1 && res.ok === 1) {
        delValue(body.key)
        ctx.body = {
          code: 200,
          msg: '更新成功'
        }
      } else {
        ctx.body = {
          code: 500,
          msg: '更新失败'
        }
      }
      return
    }
    ctx.body = {
      code: 500,
      msg: '携带参数不完整，无法更新'
    }
  }

  // 修改密码
  async changePass (ctx) {
    const { body } = ctx.request
    const obj = await getJWTPayload(ctx.header.authorization)
    const user = await UserModel.findOne({ _id: obj._id })
    if (bcryptjs.compareSync(body.oldpass, user.password)) {
      const salt = bcryptjs.genSaltSync(10)
      const pass = bcryptjs.hashSync(body.newpass, salt)
      await UserModel.updateOne(
        {
          _id: obj._id
        },
        {
          $set: { password: pass }
        }
      )
      ctx.body = {
        code: 200,
        msg: '修改密码成功'
      }
    } else {
      ctx.body = {
        code: 403,
        msg: '密码不正确，无法修改！'
      }
    }
  }

  // 收藏，取消收藏
  async setCollect (ctx) {
    const { body: { tid, title } } = ctx.request
    const obj = await getJWTPayload(ctx.header.authorization)
    const post = await PostModel.findOne({ _id: tid })
    if (!post) {
      ctx.body = {
        code: 404,
        msg: '文章不存在，无法收藏'
      }
      return
    }
    const collect = await UserCollectsModel.findOne({
      tid,
      uid: obj._id
    })
    let result = 0
    if (collect) {
      // 取消收藏
      await UserCollectsModel.deleteOne({
        tid,
        uid: obj._id
      })
    } else {
      const userCollect = new UserCollectsModel({
        tid,
        uid: obj._id,
        title
      })
      userCollect.save()
      result = 1
    }
    ctx.body = {
      code: 200,
      msg: result ? '收藏成功' : '取消成功',
      data: result
    }
  }

  // 获取收藏列表
  async getCollect (ctx) {
    const { page = 0, limit = 10 } = ctx.query
    const obj = await getJWTPayload(ctx.header.authorization)
    const result = await UserCollectsModel.getCollectList(obj._id, page, parseInt(limit))
    const total = await UserCollectsModel.find({ _id: obj._id }).countDocuments()
    ctx.body = {
      code: 200,
      data: result,
      total,
      msg: 'success'
    }
  }

  // 获取我的帖子
  async getMyPost (ctx) {
    const { uid, page = 0, limit = 10 } = ctx.query
    // const obj = await getJWTPayload(ctx.header.authorization)
    const result = await PostModel.getMyPostList(uid, page, parseInt(limit))
    const total = await PostModel.find({ uid: uid }).countDocuments()
    ctx.body = {
      code: 200,
      data: result,
      total
    }
  }

  // 删除我的帖子
  async deleteMyPost (ctx) {
    const { body: { tid } } = ctx.request
    const post = await PostModel.findOne({ _id: tid })
    if (!post) {
      ctx.body = {
        code: 404,
        msg: '该帖子不存在'
      }
      return
    }
    const obj = await getJWTPayload(ctx.header.authorization)
    if (post.isEnd === 1 || post.uid !== obj._id) {
      ctx.body = {
        code: 403,
        msg: '无权进行该操作'
      }
      return
    }
    await PostModel.deleteOne({ _id: tid })
    await CommentModel.deleteMany({
      tid
    })
    ctx.body = {
      code: 200,
      msg: '删除成功'
    }
  }

  // 获取用户信息
  async getUserInfo (ctx) {
    let { uid } = ctx.query
    if (!uid) {
      const obj = await getJWTPayload(ctx.headers.authorization)
      if (obj) {
        uid = obj._id
      } else {
        ctx.body = {
          code: 404,
          msg: '没有找到相关用户信息'
        }
        return
      }
    }
    const res = await UserModel.findById(uid)
    if (!res) {
      ctx.body = {
        code: 404,
        msg: '没有找到该用户信息'
      }
      return
    }
    const date = moment().format('YYYY-MM-DD')
    const record = await SignRecord.findOne({
      uid,
      created: {
        $gte: `${date} 00:00:00`
      }
    })
    const data = res.toJSON()
    if (record && record.uid) {
      data.isSign = true
    } else {
      data.isSign = false
    }
    ctx.body = {
      code: 200,
      data: data,
      msg: 'success'
    }
  }

  // 获取用户资料
  async getUserList (ctx) {
    const { page = 0, limit = 10, options = {} } = ctx.query
    const data = await UserModel.getUserList(page, parseInt(limit), JSON.parse(options))
    const total = await UserModel.getUserCount()
    ctx.body = {
      data,
      total,
      code: 200,
      msg: 'sucess'
    }
  }

  // 更新用户资料
  async updateUser (ctx) {
    const { body: { _id, username, password }, body } = ctx.request
    const user = await UserModel.findOne({ _id })
    if (!user) {
      ctx.body = {
        code: 404,
        msg: '没有找到该用户'
      }
    }
    if (user.username !== username) {
      const checkUserName = await UserModel.findOne({ username })
      if (checkUserName) {
        ctx.body = {
          code: 403,
          msg: '用户名已存在，无法更新'
        }
        return
      }
    }
    if (password) {
      const salt = bcryptjs.genSaltSync(10)
      const pass = bcryptjs.hashSync(password, salt)
      body.password = pass
    }
    const data = await UserModel.updateOne({ _id }, body)
    ctx.body = {
      code: 200,
      data,
      msg: '更新成功'
    }
  }

  // 检测用户是否存在
  async checkUserName (ctx) {
    const username = ctx.query.username
    let result = true
    const checkUserName = await UserModel.findOne({ username })
    if (checkUserName) {
      result = false
    }
    ctx.body = {
      code: 200,
      data: result,
      msg: 'success'
    }
  }

  // 删除用户资料
  async deleteUser (ctx) {
    const { ids } = ctx.request.body
    // const user = await UserModel.findOne({ _id: id })
    // if (!user) {
    //   ctx.body = {
    //     code: 404,
    //     msg: '该用户不存在'
    //   }
    //   return
    // }
    const data = await UserModel.deleteMany({ _id: { $in: ids } })
    if (data.ok === 1 && data.n === 1) {
      ctx.body = {
        code: 200,
        data,
        msg: '删除成功'
      }
    } else {
      ctx.body = {
        code: 500,
        data,
        msg: '删除失败'
      }
    }
  }

  // 新增用户
  async addUser (ctx) {
    let msg = ''
    let checkUser = true
    const { body: { username, name, password }, body } = ctx.request
    let user = await UserModel.findOne({ username })
    if (user) {
      msg = '用户名已存在，请重新输入'
      checkUser = false
    }
    user = await UserModel.findOne({ name })
    if (user) {
      msg = '昵称已存在，请重新输入'
      checkUser = false
    }
    if (checkUser) {
      const salt = bcryptjs.genSaltSync(10)
      const pass = bcryptjs.hashSync(password, salt)
      body.password = pass
      const user = new UserModel(body)
      const result = await user.save()
      ctx.body = {
        data: result,
        code: 200,
        msg: 'success'
      }
    } else {
      ctx.body = {
        code: 403,
        msg
      }
    }
  }

  async updateUserBatch (ctx) {
    const { body: { ids }, body } = ctx.request
    const data = await UserModel.updateMany({ _id: { $in: ids } }, body)
    ctx.body = {
      code: 200,
      data,
      msg: 'success'
    }
  }
}

export default new UserController()
